import { GrowlMessageType } from './../../components/messageBox/growMeaageType';
import { MessageBoxService } from './../../components/messageBox/messageBoxService';
import axios from 'axios';
import { MD5 } from "./MD5"

export class PrividerService {
    preLdcIp
    preStoreId
    LDCConfig
    store
    adsAbout
    StoreUser
    Token
    constructor() {
        this.preLdcIp = "localhost";
        this.preStoreId = "cfdtzn8vb0o4g4488gw8wko4k";
        this.LDCConfig = null;
        this.store = null;
    }
    static current = new PrividerService();
    //
    get fbsPort() {
        return location.protocol.indexOf("https") > -1 ? 8886 : 8887
    }
    get fbsOrigin() {
        return location.protocol + "//" + this.preLdcIp + ":" + this.fbsPort;
    }
    //http     
    doAxiosGet(url, config = null) {
        const axiosGetResponse = config ? axios.get(url, config) : axios.get(url);
        return axiosGetResponse;
    }
    doFbsGet(url, config = null) {
        return this.httpResultCallback(this.doAxiosGet(this.fbsOrigin + url, config = null));
    }
    doCloudGet(url, config = null) {
        return this.httpResultCallback(this.doAxiosGet(url, config = null));
    }
    doAxiosPost(url, config = {}) {
        const axiosGetResponse = config ? axios.post(url, config) : axios.get(url);
        return axiosGetResponse;
    }
    doCloudPost(url, body = {}): Promise<any> {
        return this.httpResultCallback(this.doAxiosPost(url, body));
    }
    doAxiosPut(url, config = {}) {
        const axiosGetResponse = config ? axios.put(url, config) : axios.get(url);
        return axiosGetResponse;
    }
    httpResultCallback(result) {
        return new Promise((resolve, reject) => {
            result.then(response => {
                const rData = response.data;
                //老的java接口会这样子返回
                if (typeof rData.code == "undefined") {
                    resolve(rData);
                }
                if (rData.code == 200) resolve(rData.data);
                else reject(rData.message);
            }).catch(error => {
                console.log(error);
                reject(error);
            })
        });
    }

    async setAdsAbout() {
        try {
            const adsAbout = (await this.doAxiosGet("http://localhost:8866/about")).data;
            PrividerService.current.doLocalstorageSetItem("adsAbout", adsAbout)
        } catch (error) {
            const adsAbout = {"ppi":96,"hardware":"Gigabyte Technology Co., Ltd. To be filled by O.E.M.","deviceType":"desktop","deviceId":"FC:AA:14:BF:5D:23","platform":"Windows","platformVersion":"6.1.7601","os":"Microsoft Windows 7 旗舰版  Service Pack 1 64-bit","appShell":"menpuji WindowsAPP 2.12.0 building 20161031","appVersion":"2.12.0","ldcVersion":"","ip":"172.16.255.129"}
            PrividerService.current.doLocalstorageSetItem("adsAbout", adsAbout)
        }
    }
    async fetchStoreIdByIDCIp(LDCIp = this.preLdcIp, config = { timeout: 600 }) {
        return await this.httpResultCallback(this.doAxiosGet("//" + LDCIp + `:${this.fbsPort}/api/system/getStoreId`, config))
    }
    async fetchLDCConfig(storeId?) {
        let url = "/api/stores/" + (storeId || this.preStoreId) + "/config/get/config?type=system.ldc";
        return await this.doCloudGet(url);
    }
    async getStore(id?) {
        try {
            let url = "/api/stores/" + (id || this.preStoreId);
            const res = await this.doCloudGet(url);
            return res;
        } catch (error) {
            throw (error)
        }
    }
    async isFbsOnline() {
        try {
            await this.doFbsGet("/api/system/isOnline")
            return true;
        } catch (error) {
            return false;
        }
    }
    async doCloudLogin(username, password) {
        let url = "/api/terminal/login/new";
        let postJson = {
            account: username,
            password: MD5.hex_md5(password)
        };
        const result = await this.doCloudPost(url, postJson);
        if (!result.user) {
            throw result;
        }
        this.StoreUser = result;
        this.Token = this.StoreUser.token;

        return this.StoreUser;
    }

    //public
    router: { navigate: (url) => {} }
    registerRouter(router) {
        this.router = router;
    }
    messageBoxService: MessageBoxService
    registerMessageBoxService(messageBoxService: MessageBoxService) {
        this.messageBoxService = messageBoxService;
    }
    errorGrow(title, content?) {
        this.messageBoxService.Growl(GrowlMessageType.Error, title, content);
    }

    navigate(path) {
        if (!this.router) {
            throw new Error("router未初始化")
        }
        this.router.navigate(path)
    }

    doLocalstorageGetItem(key) {
        const result = localStorage.getItem(key);
        if (result) return JSON.parse(result);
        return null;
    }

    doLocalstorageSetItem(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    }
}

